const http = require('http')
const fs = require('fs')
const path = require('path')
const config = require('./config')
const createHandler = require('github-webhook-handler')
const log4js = require('log4js');
const shell = require('shelljs');
const axios = require("axios");
const mdparse = require('./service/mdparse');
const {firstSync} = require('./service/articles-sync');

log4js.configure('log4js.json');
const logger = log4js.getLogger("main");

if (!shell.which('git')) {
  logger.error('Sorry, this service requires git');
  shell.exit(1);
}

try {
  if(shell.ls(path.join(config.blog.contentPath,'*.html')).length === 0){
    firstSync(config.localSource.path, config.blog.contentPath);
  }
} catch (err) {
  logger.error(err.message);
};

const handler = createHandler({ path: config.webhook.path, secret: config.webhook.secret })
logger.info('config.webhook.path:' + config.webhook.path);
logger.info('config.webhook.secret:' + config.webhook.secret);
logger.info('config.webhook.port:' + config.hookServer.port);

http.createServer(function (req, res) {
  handler(req, res, function (err) {
    res.statusCode = 404
    res.end('no such location')
  })
}).listen(config.hookServer.port)



handler.on('error', function (err) {
  logger.error(err.message);
})

handler.on('push', function (event) {
  logger.info('in push event.');
  if(shell.ls(config.localSource.path).length === 0){
    logger.error(`Local article source path [${config.localSource.path}] not exist`)
    return;
  }

  shell.cd(config.localSource.path);
  shell.exec('git pull', function(code, stdout, stderr) {
    if(code === 0){

      // add articles

      logger.info('event.payload.commits[0].added:' + event.payload.commits[0].added);
      const added = event.payload.commits[0].added;
      added.forEach(item => {
        logger.info('added file:' + item);
        mdparse(path.join(config.localSource.path, item),config.blog.contentPath)
      });
      
      // update articles
      const modified = event.payload.commits[0].modified;
      modified.forEach(item => {
        logger.info('modified file:' + item);
        mdparse(path.join(config.localSource.path, item),config.blog.contentPath)
      });

      // remove articles
      const removed = event.payload.commits[0].removed;
      removed.forEach(item => {

        logger.info('removed file:' + item);

        // 从config.blog.contentPath中删除
        logger.debug(`Delete [${item}] from blog ...`);
        shell.rm('-f',path.join(config.blog.contentPath, path.basename(item, '.md')+'.html'));

        // 从数据库中删除 
        logger.debug(`Delete [${item}] from DB...`);
        const filePath =  path.basename(item, '.md');
        axios.delete(config.apiServer.url + '/articles/path/' + filePath)
          .catch(function (error) {
            if (error.response) {
              logger.error(error.response.status);
            } else {
              logger.error( error.message);
            }
          });
      });

      // 复制images
      shell.cp('-rfu', config.localSource.path + '/images', config.blog.contentPath);
      logger.info(`Copy [${config.localSource.path}/images] to [${config.localSource.path}] completed.`)

      logger.info('Article synchronized!');
    } else {
      logger.error('Git pull failed:' + stderr);
    }
  }); 
})

// handler.on('issues', function (event) {
//   console.log('Received an issue event for %s action=%s: #%d %s',
//     event.payload.repository.name,
//     event.payload.action,
//     event.payload.issue.number,
//     event.payload.issue.title)
// })

logger.info('Webhook service run at ' + config.hookServer.port);